<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>浏览器代理工具 - Web 管理界面</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: #f5f5f7;
            color: #1d1d1f;
            line-height: 1.6;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        
        .header {
            background: white;
            border-radius: 12px;
            padding: 30px;
            margin-bottom: 20px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.07);
        }
        
        .header h1 {
            font-size: 2.5em;
            font-weight: 600;
            margin-bottom: 10px;
            color: #1d1d1f;
        }
        
        .header p {
            color: #86868b;
            font-size: 1.1em;
        }
        
        .card {
            background: white;
            border-radius: 12px;
            padding: 25px;
            margin-bottom: 20px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.07);
        }
        
        .card h2 {
            font-size: 1.5em;
            font-weight: 600;
            margin-bottom: 20px;
            color: #1d1d1f;
        }
        
        .status-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 20px;
        }
        
        .status-item {
            background: #f6f6f6;
            border-radius: 8px;
            padding: 20px;
            text-align: center;
        }
        
        .status-item.active {
            background: #d4edda;
            border: 2px solid #28a745;
        }
        
        .status-item.inactive {
            background: #f8d7da;
            border: 2px solid #dc3545;
        }
        
        .btn {
            background: #007aff;
            color: white;
            border: none;
            border-radius: 8px;
            padding: 12px 24px;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
            margin: 5px;
        }
        
        .btn:hover {
            background: #0056b3;
            transform: translateY(-1px);
        }
        
        .btn.danger {
            background: #ff3b30;
        }
        
        .btn.danger:hover {
            background: #d70015;
        }
        
        .btn.success {
            background: #28a745;
        }
        
        .btn.success:hover {
            background: #218838;
        }
        
        .form-group {
            margin-bottom: 15px;
        }
        
        .form-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 15px;
        }
        
        .form-row .form-group {
            margin-bottom: 15px;
        }
        
        @media (max-width: 600px) {
            .form-row {
                grid-template-columns: 1fr;
            }
            
            .modal-content {
                margin: 1% auto;
                padding: 20px;
                max-width: 95%;
            }
        }
        
        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: #1d1d1f;
        }
        
        .form-group input, .form-group select, .form-group textarea {
            width: 100%;
            padding: 12px;
            border: 1px solid #d2d2d7;
            border-radius: 8px;
            font-size: 16px;
            background: white;
            font-family: inherit;
        }
        
        .form-group textarea {
            resize: vertical;
            min-height: 80px;
        }
        
        .form-group input:focus, .form-group select:focus, .form-group textarea:focus {
            outline: none;
            border-color: #007aff;
            box-shadow: 0 0 0 3px rgba(0, 122, 255, 0.1);
        }
        
        .rules-list {
            margin-top: 20px;
        }
        
        .rule-item {
            background: #f6f6f6;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 10px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-left: 4px solid #007aff;
        }
        
        .rule-item.mock {
            border-left-color: #28a745;
            background: #f8fff9;
        }
        
        .rule-item.disabled {
            opacity: 0.6;
            background: #f0f0f0;
            border-left-color: #6c757d;
        }
        
        .rule-info {
            flex: 1;
        }
        
        .rule-pattern {
            font-weight: 600;
            color: #007aff;
        }
        
        .rule-target {
            color: #86868b;
            font-size: 0.9em;
        }
        
        .rule-type {
            display: inline-block;
            padding: 2px 8px;
            border-radius: 12px;
            font-size: 0.8em;
            font-weight: 500;
            margin-left: 8px;
        }
        
        .rule-type.proxy {
            background: #e3f2fd;
            color: #1976d2;
        }
        
        .rule-type.mock {
            background: #e8f5e8;
            color: #2e7d32;
        }
        
        .rule-status {
            display: inline-block;
            padding: 2px 8px;
            border-radius: 12px;
            font-size: 0.8em;
            font-weight: 500;
            margin-left: 8px;
        }
        
        .rule-status.enabled {
            background: #d4edda;
            color: #155724;
        }
        
        .rule-status.disabled {
            background: #f8d7da;
            color: #721c24;
        }
        
        .rule-actions {
            display: flex;
            gap: 10px;
        }
        
        .btn-small {
            padding: 6px 12px;
            font-size: 14px;
        }
        
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            z-index: 1000;
            overflow-y: auto;
            padding: 20px 0;
        }
        
        .modal-content {
            background: white;
            border-radius: 12px;
            padding: 30px;
            margin: 2% auto;
            max-width: 600px;
            width: 90%;
            max-height: 90vh;
            overflow-y: auto;
            position: relative;
        }
        
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        
        .modal-header h3 {
            font-size: 1.3em;
            font-weight: 600;
        }
        
        .close {
            background: none;
            border: none;
            font-size: 24px;
            cursor: pointer;
            color: #86868b;
        }
        
        .alert {
            padding: 12px 16px;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        
        .alert.success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .alert.error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        /* 导航选项卡样式 */
        .nav-tabs {
            display: flex;
            margin-top: 20px;
            border-bottom: 2px solid #e5e5e7;
        }
        
        .nav-tab {
            background: none;
            border: none;
            padding: 12px 24px;
            font-size: 16px;
            font-weight: 500;
            color: #86868b;
            cursor: pointer;
            border-bottom: 2px solid transparent;
            transition: all 0.3s ease;
        }
        
        .nav-tab:hover {
            color: #007aff;
        }
        
        .nav-tab.active {
            color: #007aff;
            border-bottom-color: #007aff;
        }
        
        /* 选项卡内容样式 */
        .tab-content {
            display: none;
        }
        
        .tab-content.active {
            display: block;
        }
        
        /* 日志页面样式 */
        .log-filters {
            background: #f6f6f6;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
        }
        
        .filter-row {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            align-items: end;
        }
        
        .log-container {
            background: #f9f9f9;
            border-radius: 8px;
            overflow: hidden;
            max-height: 600px;
            border: 1px solid #e5e5e7;
        }
        
        .log-header {
            display: grid;
            grid-template-columns: 180px 80px 1fr;
            gap: 15px;
            padding: 12px 15px;
            background: #e5e5e7;
            font-weight: 600;
            color: #1d1d1f;
            border-bottom: 1px solid #d2d2d7;
        }
        
        .log-content {
            max-height: 550px;
            overflow-y: auto;
        }
        
        .log-entry {
            display: grid;
            grid-template-columns: 180px 80px 1fr;
            gap: 15px;
            padding: 10px 15px;
            border-bottom: 1px solid #e5e5e7;
            font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
            font-size: 13px;
        }
        
        .log-entry:hover {
            background: #f0f0f0;
        }
        
        .log-entry.level-INFO {
            border-left: 3px solid #28a745;
        }
        
        .log-entry.level-ERROR {
            border-left: 3px solid #dc3545;
            background: #fff5f5;
        }
        
        .log-entry.level-DEBUG {
            border-left: 3px solid #6c757d;
        }
        
        .log-time {
            color: #666;
            font-weight: 500;
        }
        
        .log-level {
            font-weight: 600;
            text-align: center;
            padding: 2px 6px;
            border-radius: 4px;
            font-size: 11px;
        }
        
        .log-level.INFO {
            background: #d4edda;
            color: #155724;
        }
        
        .log-level.ERROR {
            background: #f8d7da;
            color: #721c24;
        }
        
        .log-level.DEBUG {
            background: #e2e3e5;
            color: #383d41;
        }
        
        .log-message {
            word-break: break-word;
            line-height: 1.4;
        }
        
        .log-loading {
            text-align: center;
            padding: 40px;
            color: #86868b;
        }
        
        .log-empty {
            text-align: center;
            padding: 40px;
            color: #86868b;
        }
        
        /* 证书配置页面样式 */
        .cert-info {
            margin-top: 20px;
        }
        
        .cert-status {
            background: #f6f6f6;
            border-radius: 8px;
            padding: 20px;
            margin: 20px 0;
        }
        
        .cert-instructions {
            margin: 20px 0;
        }
        
        .install-method {
            background: #f9f9f9;
            border-radius: 8px;
            padding: 20px;
            margin: 15px 0;
            border-left: 4px solid #007aff;
        }
        
        .install-method h4 {
            color: #007aff;
            margin-bottom: 10px;
        }
        
        .code-block {
            background: #1d1d1f;
            color: #f6f6f6;
            padding: 15px;
            border-radius: 6px;
            font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
            position: relative;
            margin: 10px 0;
        }
        
        .code-block code {
            font-size: 14px;
        }
        
        .code-block .btn {
            position: absolute;
            top: 10px;
            right: 10px;
            padding: 4px 8px;
            font-size: 12px;
        }
        
        .manual-steps {
            background: white;
            border: 1px solid #e5e5e7;
            border-radius: 6px;
            padding: 15px;
            margin: 10px 0;
        }
        
        .manual-steps ol {
            margin-left: 20px;
        }
        
        .manual-steps li {
            margin: 8px 0;
        }
        
        .proxy-settings {
            background: #e8f4fd;
            border: 1px solid #bee5eb;
            border-radius: 6px;
            padding: 15px;
            margin: 10px 0;
        }
        
        .proxy-settings ul {
            margin-left: 20px;
        }
        
        .cert-download {
            background: #f6f6f6;
            border-radius: 8px;
            padding: 20px;
            margin: 20px 0;
        }
        
        .cert-download code {
            background: #1d1d1f;
            color: #f6f6f6;
            padding: 4px 8px;
            border-radius: 4px;
            font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>浏览器代理工具</h1>
            <p>通过 Web 界面管理代理服务器和配置规则</p>
            
            <!-- 导航选项卡 -->
            <div class="nav-tabs">
                <button class="nav-tab active" onclick="showTab('dashboard')">控制面板</button>
                <button class="nav-tab" onclick="showTab('logs')">日志查看</button>
                <button class="nav-tab" onclick="showTab('cert')">证书配置</button>
            </div>
        </div>

        <!-- 控制面板内容 -->
        <div id="dashboard-content" class="tab-content active">
            <!-- 状态监控 -->
            <div class="card">
                <h2>服务状态</h2>
                <div class="status-grid">
                    <div class="status-item" id="proxy-server-status">
                        <h3>代理服务器</h3>
                        <p id="proxy-server-text">检查中...</p>
                        <button class="btn" id="proxy-server-btn" onclick="toggleProxyServer()">启动</button>
                    </div>
                    <div class="status-item" id="system-proxy-status">
                        <h3>系统代理</h3>
                        <p id="system-proxy-text">检查中...</p>
                        <button class="btn" id="system-proxy-btn" onclick="toggleSystemProxy()">启用</button>
                    </div>
                </div>
            </div>

            <!-- 代理规则管理 -->
            <div class="card">
                <h2>代理规则</h2>
                <button class="btn success" onclick="showAddRuleModal()">添加规则</button>
                <div class="rules-list" id="rules-list">
                    <!-- 规则列表将通过 JavaScript 动态生成 -->
                </div>
            </div>
        </div>

        <!-- 日志查看内容 -->
        <div id="logs-content" class="tab-content">
            <div class="card">
                <h2>日志查看</h2>
                
                <!-- 日志过滤器 -->
                <div class="log-filters">
                    <div class="filter-row">
                        <div class="form-group">
                            <label for="log-rule-filter">按规则过滤</label>
                            <select id="log-rule-filter">
                                <option value="">全部规则</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="log-level-filter">日志级别</label>
                            <select id="log-level-filter">
                                <option value="">全部级别</option>
                                <option value="INFO">信息</option>
                                <option value="ERROR">错误</option>
                                <option value="DEBUG">调试</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="log-date-filter">日期过滤</label>
                            <input type="date" id="log-date-filter">
                        </div>
                        <div class="form-group">
                            <button class="btn" onclick="loadLogs()">刷新日志</button>
                            <button class="btn" onclick="clearLogFilters()">清除过滤</button>
                        </div>
                    </div>
                </div>
                
                <!-- 日志内容 -->
                <div class="log-container">
                    <div class="log-header">
                        <span>时间</span>
                        <span>级别</span>
                        <span>内容</span>
                    </div>
                    <div class="log-content" id="log-content">
                        <div class="log-loading">加载中...</div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 证书安装指导内容 -->
        <div id="cert-content" class="tab-content">
            <div class="card">
                <h2>HTTPS证书配置</h2>
                <div class="cert-info">
                    <div class="alert" style="background: #fff3cd; color: #856404; border: 1px solid #ffeaa7;">
                        <h3>⚠️ 为什么需要安装证书？</h3>
                        <p>当代理服务器拦截HTTPS流量时，它会使用自己的证书。浏览器默认不信任这个证书，所以会显示"连接不是专用连接"的警告。</p>
                        <p>安装mitmproxy的CA证书后，浏览器就会信任代理服务器的证书，从而正常访问HTTPS网站。</p>
                    </div>
                    
                    <div class="cert-status">
                        <h3>📋 证书状态</h3>
                        <div id="cert-status-info">检查中...</div>
                    </div>
                    
                    <div class="cert-instructions">
                        <h3>🔧 安装步骤</h3>
                        
                        <div class="install-method">
                            <h4>方法一：自动安装（推荐）</h4>
                            <div class="code-block">
                                <code>python install_cert.py</code>
                                <button class="btn btn-small" onclick="copyToClipboard('python install_cert.py')">复制</button>
                            </div>
                            <p>在项目目录下运行此命令，工具会自动检测系统并安装证书。</p>
                        </div>
                        
                        <div class="install-method">
                            <h4>方法二：手动安装</h4>
                            <div class="manual-steps" id="manual-steps">
                                <!-- 手动安装步骤将通过JavaScript动态生成 -->
                            </div>
                        </div>
                        
                        <div class="install-method">
                            <h4>方法三：仅HTTP代理（临时解决）</h4>
                            <p>如果只需要代理HTTP流量，可以在浏览器中只设置HTTP代理，不设置HTTPS代理。</p>
                            <div class="proxy-settings">
                                <p><strong>代理设置：</strong></p>
                                <ul>
                                    <li>HTTP代理: 127.0.0.1:8080</li>
                                    <li>HTTPS代理: 留空或禁用</li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    
                    <div class="cert-download">
                        <h3>📥 证书文件下载</h3>
                        <p>证书文件位置: <code id="cert-path">~/.mitmproxy/mitmproxy-ca-cert.pem</code></p>
                        <button class="btn" onclick="downloadCertificate()">下载证书文件</button>
                        <button class="btn" onclick="openCertDirectory()">打开证书目录</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 添加/编辑规则模态框 -->
    <div class="modal" id="rule-modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 id="modal-title">添加规则</h3>
                <button class="close" onclick="hideRuleModal()">&times;</button>
            </div>
            <form id="rule-form">
                <div class="form-group">
                    <label for="pattern">匹配模式</label>
                    <input type="text" id="pattern" name="pattern" placeholder="例如: api.example.com" required>
                </div>
                
                <div class="form-row">
                    <div class="form-group">
                        <label for="rule_type">规则类型</label>
                        <select id="rule_type" name="rule_type" onchange="toggleRuleTypeFields()">
                            <option value="proxy">代理转发</option>
                            <option value="mock">Mock响应</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="enabled">启用状态</label>
                        <select id="enabled" name="enabled">
                            <option value="true">启用</option>
                            <option value="false">禁用</option>
                        </select>
                    </div>
                </div>
                
                <!-- 代理规则字段 -->
                <div id="proxy-fields">
                    <div class="form-group">
                        <label for="strip_prefix">去除前缀 (可选)</label>
                        <input type="text" id="strip_prefix" name="strip_prefix" placeholder="例如: /api">
                    </div>
                    <div class="form-row">
                        <div class="form-group">
                            <label for="scheme">协议</label>
                            <select id="scheme" name="scheme">
                                <option value="http">HTTP</option>
                                <option value="https">HTTPS</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="port">目标端口</label>
                            <input type="number" id="port" name="port" placeholder="例如: 8000">
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="host">目标主机</label>
                        <input type="text" id="host" name="host" placeholder="例如: 127.0.0.1">
                    </div>
                </div>
                
                <!-- Mock规则字段 -->
                <div id="mock-fields" style="display: none;">
                    <div class="form-row">
                        <div class="form-group">
                            <label for="mock_status">HTTP状态码</label>
                            <input type="number" id="mock_status" name="mock_status" placeholder="200" value="200" min="100" max="599">
                        </div>
                        <div class="form-group">
                            <label for="mock_data_source">数据源</label>
                            <select id="mock_data_source" name="mock_data_source" onchange="toggleMockDataFields()">
                                <option value="inline">内联内容</option>
                                <option value="file">外部文件</option>
                            </select>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="mock_content_type">内容类型</label>
                        <select id="mock_content_type" name="mock_content_type">
                            <option value="application/json">application/json</option>
                            <option value="text/html">text/html</option>
                            <option value="text/plain">text/plain</option>
                            <option value="application/xml">application/xml</option>
                        </select>
                    </div>
                    <div class="form-group" id="mock-inline-field">
                        <label for="mock_content">Mock内容</label>
                        <textarea id="mock_content" name="mock_content" rows="4" placeholder='{"message": "Hello from Mock API"}'></textarea>
                    </div>
                    <div class="form-group" id="mock-file-field" style="display: none;">
                        <label for="mock_content_file">Mock文件路径</label>
                        <input type="text" id="mock_content_file" name="mock_content_file" placeholder="./mocks/users.json">
                    </div>
                    <div class="form-group">
                        <label for="mock_headers">自定义响应头 (可选，JSON格式)</label>
                        <textarea id="mock_headers" name="mock_headers" rows="2" placeholder='{"X-Mock": "true", "Cache-Control": "no-cache"}'></textarea>
                    </div>
                </div>
                <div style="text-align: right;">
                    <button type="button" class="btn" onclick="hideRuleModal()">取消</button>
                    <button type="submit" class="btn success">保存</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        let currentEditIndex = -1;

        // 页面加载时初始化
        window.onload = function() {
            checkStatus();
            loadRules();
            loadRuleOptions();
            setInterval(checkStatus, 8000); // 每8秒检查一次状态
        };

        // 检查服务状态
        async function checkStatus() {
            try {
                const response = await fetch('/api/proxy/status');
                const data = await response.json();
                
                updateProxyServerStatus(data.server_running);
                updateSystemProxyStatus(data.system_proxy);
            } catch (error) {
                console.error('检查状态失败:', error);
            }
        }

        // 更新代理服务器状态
        function updateProxyServerStatus(running) {
            const statusEl = document.getElementById('proxy-server-status');
            const textEl = document.getElementById('proxy-server-text');
            const btnEl = document.getElementById('proxy-server-btn');

            if (running) {
                statusEl.className = 'status-item active';
                textEl.textContent = '运行中';
                btnEl.textContent = '停止';
                btnEl.className = 'btn danger';
            } else {
                statusEl.className = 'status-item inactive';
                textEl.textContent = '已停止';
                btnEl.textContent = '启动';
                btnEl.className = 'btn';
            }
        }

        // 更新系统代理状态
        function updateSystemProxyStatus(status) {
            const statusEl = document.getElementById('system-proxy-status');
            const textEl = document.getElementById('system-proxy-text');
            const btnEl = document.getElementById('system-proxy-btn');

            const enabled = status.http_enabled || status.https_enabled;
            if (enabled) {
                statusEl.className = 'status-item active';
                textEl.textContent = '已启用';
                btnEl.textContent = '禁用';
                btnEl.className = 'btn danger';
            } else {
                statusEl.className = 'status-item inactive';
                textEl.textContent = '已禁用';
                btnEl.textContent = '启用';
                btnEl.className = 'btn';
            }
        }

        // 切换代理服务器状态
        async function toggleProxyServer() {
            const btnEl = document.getElementById('proxy-server-btn');
            const isRunning = btnEl.textContent === '停止';
            
            try {
                const endpoint = isRunning ? '/api/proxy/stop' : '/api/proxy/start';
                const response = await fetch(endpoint, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({})
                });
                const data = await response.json();
                
                if (data.success) {
                    checkStatus();
                } else {
                    alert('操作失败');
                }
            } catch (error) {
                console.error('操作失败:', error);
                alert('操作失败');
            }
        }

        // 切换系统代理状态
        async function toggleSystemProxy() {
            const btnEl = document.getElementById('system-proxy-btn');
            const isEnabled = btnEl.textContent === '禁用';
            
            try {
                const endpoint = isEnabled ? '/api/system-proxy/disable' : '/api/system-proxy/enable';
                const body = isEnabled ? {} : { host: '127.0.0.1', port: 8080 };
                
                const response = await fetch(endpoint, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(body)
                });
                
                const data = await response.json();
                if (data.success) {
                    checkStatus();
                } else {
                    alert('操作失败');
                }
            } catch (error) {
                console.error('操作失败:', error);
                alert('操作失败');
            }
        }

        // 加载规则列表
        async function loadRules() {
            try {
                const response = await fetch('/api/config');
                const config = await response.json();
                displayRules(config.rules || []);
            } catch (error) {
                console.error('加载规则失败:', error);
            }
        }

        // 显示规则列表
        function displayRules(rules) {
            const listEl = document.getElementById('rules-list');
            listEl.innerHTML = '';

            rules.forEach((rule, index) => {
                const ruleEl = document.createElement('div');
                
                // 确定规则类型和状态
                const isMockRule = rule.type === 'mock' || rule.mock_response;
                const isEnabled = rule.enabled !== false; // 默认启用
                
                ruleEl.className = 'rule-item';
                if (isMockRule) ruleEl.classList.add('mock');
                if (!isEnabled) ruleEl.classList.add('disabled');
                
                // 构建显示内容
                let targetText = '';
                if (isMockRule) {
                    const mockResponse = rule.mock_response || {};
                    const status = mockResponse.status || 200;
                    const contentType = mockResponse.content_type || 'application/json';
                    const hasFile = mockResponse.content_file;
                    const dataSource = hasFile ? `文件: ${mockResponse.content_file}` : '内联内容';
                    targetText = `Mock响应 (${status}, ${contentType}) - ${dataSource}`;
                } else {
                    const target = rule.target || {};
                    targetText = `${target.scheme || 'http'}://${target.host || 'localhost'}:${target.port || 80}`;
                    const stripText = rule.strip_prefix ? ` (去除前缀: ${rule.strip_prefix})` : '';
                    targetText += stripText;
                }
                
                // 规则类型和状态标签
                const typeLabel = isMockRule ? '<span class="rule-type mock">Mock</span>' : '<span class="rule-type proxy">代理</span>';
                const statusLabel = isEnabled ? '<span class="rule-status enabled">启用</span>' : '<span class="rule-status disabled">禁用</span>';
                
                ruleEl.innerHTML = `
                    <div class="rule-info">
                        <div class="rule-pattern">
                            ${rule.pattern}
                            ${typeLabel}
                            ${statusLabel}
                        </div>
                        <div class="rule-target">${targetText}</div>
                    </div>
                    <div class="rule-actions">
                        <button class="btn btn-small ${isEnabled ? 'danger' : 'success'}" onclick="toggleRuleEnabled(${index})">${isEnabled ? '禁用' : '启用'}</button>
                        <button class="btn btn-small" onclick="editRule(${index})">编辑</button>
                        <button class="btn btn-small danger" onclick="deleteRule(${index})">删除</button>
                    </div>
                `;
                
                listEl.appendChild(ruleEl);
            });
        }

        // 显示添加规则模态框
        function showAddRuleModal() {
            currentEditIndex = -1;
            document.getElementById('modal-title').textContent = '添加规则';
            document.getElementById('rule-form').reset();
            document.getElementById('rule_type').value = 'proxy';
            document.getElementById('enabled').value = 'true';
            toggleRuleTypeFields();
            document.getElementById('rule-modal').style.display = 'block';
        }
        
        // 切换规则类型字段显示
        function toggleRuleTypeFields() {
            const ruleType = document.getElementById('rule_type').value;
            const proxyFields = document.getElementById('proxy-fields');
            const mockFields = document.getElementById('mock-fields');
            
            if (ruleType === 'mock') {
                proxyFields.style.display = 'none';
                mockFields.style.display = 'block';
                // Mock规则不需要host和port为必填
                document.getElementById('host').removeAttribute('required');
                document.getElementById('port').removeAttribute('required');
            } else {
                proxyFields.style.display = 'block';
                mockFields.style.display = 'none';
                // 代理规则需要host和port为必填
                document.getElementById('host').setAttribute('required', '');
                document.getElementById('port').setAttribute('required', '');
            }
        }
        
        // 切换Mock数据源字段显示
        function toggleMockDataFields() {
            const dataSource = document.getElementById('mock_data_source').value;
            const inlineField = document.getElementById('mock-inline-field');
            const fileField = document.getElementById('mock-file-field');
            
            if (dataSource === 'file') {
                inlineField.style.display = 'none';
                fileField.style.display = 'block';
            } else {
                inlineField.style.display = 'block';
                fileField.style.display = 'none';
            }
        }
        
        // 切换规则启用/禁用状态
        async function toggleRuleEnabled(index) {
            try {
                const response = await fetch(`/api/rules/${index}/toggle`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' }
                });
                
                if (response.ok) {
                    loadRules();
                } else {
                    alert('切换状态失败');
                }
            } catch (error) {
                console.error('切换状态失败:', error);
                alert('切换状态失败');
            }
        }

        // 编辑规则
        async function editRule(index) {
            try {
                const response = await fetch('/api/config');
                const config = await response.json();
                const rule = config.rules[index];
                
                currentEditIndex = index;
                document.getElementById('modal-title').textContent = '编辑规则';
                document.getElementById('pattern').value = rule.pattern || '';
                document.getElementById('enabled').value = rule.enabled !== false ? 'true' : 'false';
                
                // 判断规则类型
                const isMockRule = rule.type === 'mock' || rule.mock_response;
                document.getElementById('rule_type').value = isMockRule ? 'mock' : 'proxy';
                
                if (isMockRule) {
                    // 填充Mock规则字段
                    const mockResponse = rule.mock_response || {};
                    document.getElementById('mock_status').value = mockResponse.status || 200;
                    document.getElementById('mock_content_type').value = mockResponse.content_type || 'application/json';
                    
                    if (mockResponse.content_file) {
                        document.getElementById('mock_data_source').value = 'file';
                        document.getElementById('mock_content_file').value = mockResponse.content_file;
                        document.getElementById('mock_content').value = '';
                    } else {
                        document.getElementById('mock_data_source').value = 'inline';
                        document.getElementById('mock_content').value = mockResponse.content || '';
                        document.getElementById('mock_content_file').value = '';
                    }
                    
                    // 填充自定义头部
                    const headers = mockResponse.headers || {};
                    document.getElementById('mock_headers').value = Object.keys(headers).length > 0 ? JSON.stringify(headers, null, 2) : '';
                } else {
                    // 填充代理规则字段
                    document.getElementById('strip_prefix').value = rule.strip_prefix || '';
                    document.getElementById('scheme').value = rule.target?.scheme || 'http';
                    document.getElementById('host').value = rule.target?.host || '';
                    document.getElementById('port').value = rule.target?.port || '';
                }
                
                toggleRuleTypeFields();
                toggleMockDataFields();
                document.getElementById('rule-modal').style.display = 'block';
            } catch (error) {
                console.error('加载规则失败:', error);
            }
        }

        // 删除规则
        async function deleteRule(index) {
            if (confirm('确定要删除这条规则吗？')) {
                try {
                    const response = await fetch(`/api/rules/${index}`, { method: 'DELETE' });
                    if (response.ok) {
                        loadRules();
                    } else {
                        alert('删除失败');
                    }
                } catch (error) {
                    console.error('删除失败:', error);
                    alert('删除失败');
                }
            }
        }

        // 隐藏规则模态框
        function hideRuleModal() {
            document.getElementById('rule-modal').style.display = 'none';
        }

        // 处理规则表单提交
        document.getElementById('rule-form').addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const formData = new FormData(e.target);
            const ruleType = formData.get('rule_type');
            
            const rule = {
                pattern: formData.get('pattern'),
                enabled: formData.get('enabled') === 'true'
            };
            
            if (ruleType === 'mock') {
                // Mock规则
                rule.type = 'mock';
                rule.mock_response = {
                    status: parseInt(formData.get('mock_status')) || 200,
                    content_type: formData.get('mock_content_type')
                };
                
                // 处理Mock数据源
                if (formData.get('mock_data_source') === 'file') {
                    rule.mock_response.content_file = formData.get('mock_content_file');
                } else {
                    rule.mock_response.content = formData.get('mock_content');
                }
                
                // 处理自定义头部
                const mockHeaders = formData.get('mock_headers');
                if (mockHeaders && mockHeaders.trim()) {
                    try {
                        rule.mock_response.headers = JSON.parse(mockHeaders);
                    } catch (error) {
                        alert('自定义响应头格式错误，请检查JSON格式');
                        return;
                    }
                }
            } else {
                // 代理规则
                rule.target = {
                    scheme: formData.get('scheme'),
                    host: formData.get('host'),
                    port: parseInt(formData.get('port'))
                };
                
                if (formData.get('strip_prefix')) {
                    rule.strip_prefix = formData.get('strip_prefix');
                }
            }
            
            try {
                let response;
                if (currentEditIndex >= 0) {
                    response = await fetch(`/api/rules/${currentEditIndex}`, {
                        method: 'PUT',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify(rule)
                    });
                } else {
                    response = await fetch('/api/rules', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify(rule)
                    });
                }
                
                if (response.ok) {
                    hideRuleModal();
                    loadRules();
                } else {
                    const errorData = await response.json();
                    alert('保存失败: ' + (errorData.error || '未知错误'));
                }
            } catch (error) {
                console.error('保存失败:', error);
                alert('保存失败: ' + error.message);
            }
        });

        // 选项卡切换功能
        function showTab(tabName) {
            // 隐藏所有选项卡内容
            document.querySelectorAll('.tab-content').forEach(content => {
                content.classList.remove('active');
            });
            
            // 移除所有选项卡的active状态
            document.querySelectorAll('.nav-tab').forEach(tab => {
                tab.classList.remove('active');
            });
            
            // 显示选中的选项卡内容
            document.getElementById(tabName + '-content').classList.add('active');
            
            // 激活选中的选项卡
            event.target.classList.add('active');
            
            // 如果切换到日志页面，加载日志
            if (tabName === 'logs') {
                loadLogs();
            }
            
            // 如果切换到证书页面，检查证书状态
            if (tabName === 'cert') {
                checkCertificateStatus();
                generateManualSteps();
            }
        }

        // 加载规则选项到过滤器
        async function loadRuleOptions() {
            try {
                const response = await fetch('/api/config');
                const config = await response.json();
                const ruleFilter = document.getElementById('log-rule-filter');
                
                // 清空现有选项（保留"全部规则"）
                ruleFilter.innerHTML = '<option value="">全部规则</option>';
                
                // 添加规则选项
                (config.rules || []).forEach((rule, index) => {
                    const option = document.createElement('option');
                    option.value = rule.pattern;
                    option.textContent = rule.pattern;
                    ruleFilter.appendChild(option);
                });
            } catch (error) {
                console.error('加载规则选项失败:', error);
            }
        }

        // 加载日志
        async function loadLogs() {
            const logContent = document.getElementById('log-content');
            logContent.innerHTML = '<div class="log-loading">加载中...</div>';
            
            try {
                const ruleFilter = document.getElementById('log-rule-filter').value;
                const levelFilter = document.getElementById('log-level-filter').value;
                const dateFilter = document.getElementById('log-date-filter').value;
                
                const params = new URLSearchParams();
                if (ruleFilter) params.append('rule', ruleFilter);
                if (levelFilter) params.append('level', levelFilter);
                if (dateFilter) params.append('date', dateFilter);
                
                const response = await fetch(`/api/logs?${params.toString()}`);
                const data = await response.json();
                
                displayLogs(data.logs || []);
            } catch (error) {
                console.error('加载日志失败:', error);
                logContent.innerHTML = '<div class="log-empty">加载日志失败</div>';
            }
        }

        // 显示日志
        function displayLogs(logs) {
            const logContent = document.getElementById('log-content');
            
            if (logs.length === 0) {
                logContent.innerHTML = '<div class="log-empty">没有找到匹配的日志</div>';
                return;
            }
            
            logContent.innerHTML = '';
            
            logs.forEach(log => {
                const logEntry = document.createElement('div');
                logEntry.className = `log-entry level-${log.level || 'INFO'}`;
                
                logEntry.innerHTML = `
                    <div class="log-time">${log.timestamp || ''}</div>
                    <div class="log-level ${log.level || 'INFO'}">${log.level || 'INFO'}</div>
                    <div class="log-message">${escapeHtml(log.message || '')}</div>
                `;
                
                logContent.appendChild(logEntry);
            });
        }

        // 清除日志过滤器
        function clearLogFilters() {
            document.getElementById('log-rule-filter').value = '';
            document.getElementById('log-level-filter').value = '';
            document.getElementById('log-date-filter').value = '';
            loadLogs();
        }

        // HTML转义函数
        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }

        // 证书相关功能
        async function checkCertificateStatus() {
            const statusInfo = document.getElementById('cert-status-info');
            statusInfo.innerHTML = '检查中...';
            
            try {
                const response = await fetch('/api/cert/status');
                const data = await response.json();
                
                if (data.exists) {
                    statusInfo.innerHTML = `
                        <div style="color: #28a745;">
                            ✅ 证书文件已存在<br>
                            📍 位置: ${data.path}<br>
                            📅 创建时间: ${data.created_at}
                        </div>
                    `;
                    document.getElementById('cert-path').textContent = data.path;
                } else {
                    statusInfo.innerHTML = `
                        <div style="color: #dc3545;">
                            ❌ 证书文件不存在<br>
                            💡 请先启动代理服务器生成证书
                        </div>
                    `;
                }
            } catch (error) {
                console.error('检查证书状态失败:', error);
                statusInfo.innerHTML = `
                    <div style="color: #dc3545;">
                        ❌ 检查证书状态失败
                    </div>
                `;
            }
        }
        
        function generateManualSteps() {
            const manualSteps = document.getElementById('manual-steps');
            const userAgent = navigator.userAgent;
            let steps = '';
            
            if (userAgent.includes('Mac')) {
                steps = `
                    <h5>🍎 macOS 手动安装步骤:</h5>
                    <ol>
                        <li>双击证书文件打开钥匙串访问</li>
                        <li>选择"系统"钥匙串</li>
                        <li>找到"mitmproxy"证书，双击打开</li>
                        <li>展开"信任"部分</li>
                        <li>将"使用此证书时"设置为"始终信任"</li>
                        <li>关闭窗口并输入密码确认</li>
                    </ol>
                `;
            } else if (userAgent.includes('Windows')) {
                steps = `
                    <h5>🪟 Windows 手动安装步骤:</h5>
                    <ol>
                        <li>以管理员身份运行命令提示符</li>
                        <li>执行命令: <code>certutil -addstore -f Root "证书文件路径"</code></li>
                    </ol>
                    <p>或者:</p>
                    <ol>
                        <li>双击证书文件</li>
                        <li>点击"安装证书"</li>
                        <li>选择"本地计算机"</li>
                        <li>选择"将所有证书都放入下列存储"</li>
                        <li>选择"受信任的根证书颁发机构"</li>
                        <li>完成安装</li>
                    </ol>
                `;
            } else {
                steps = `
                    <h5>🐧 Linux 手动安装步骤:</h5>
                    <ol>
                        <li>复制证书到系统目录:<br>
                            <code>sudo cp ~/.mitmproxy/mitmproxy-ca-cert.pem /usr/local/share/ca-certificates/mitmproxy-ca-cert.crt</code>
                        </li>
                        <li>更新证书存储:<br>
                            <code>sudo update-ca-certificates</code>
                        </li>
                    </ol>
                `;
            }
            
            manualSteps.innerHTML = steps;
        }
        
        function copyToClipboard(text) {
            navigator.clipboard.writeText(text).then(() => {
                // 临时改变按钮文本
                const button = event.target;
                const originalText = button.textContent;
                button.textContent = '已复制!';
                setTimeout(() => {
                    button.textContent = originalText;
                }, 2000);
            }).catch(err => {
                console.error('复制失败:', err);
                alert('复制失败，请手动复制');
            });
        }
        
        async function downloadCertificate() {
            try {
                const response = await fetch('/api/cert/download');
                if (response.ok) {
                    const blob = await response.blob();
                    const url = window.URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = 'mitmproxy-ca-cert.pem';
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                    window.URL.revokeObjectURL(url);
                } else {
                    alert('下载失败');
                }
            } catch (error) {
                console.error('下载失败:', error);
                alert('下载失败');
            }
        }
        
        function openCertDirectory() {
            // 这个功能需要后端支持，暂时显示路径
            alert('证书目录路径: ~/.mitmproxy/\n\n请在文件管理器中打开此路径');
        }
    </script>
</body>
</html> 